import base64
import uuid
from flask import jsonify
import os

def api_response(data=None, message="", code=200, status_code=200):
    """统一的API响应格式"""
    response = {
        "code": code,
        "message": message
    }
    if data is not None:
        response["data"] = data
    return jsonify(response), status_code

def process_image(app, image_data, folder_type, format='png'):
    """统一的图像处理函数"""
    try:
        if isinstance(image_data, str) and image_data.startswith('data:'):
            # 处理Base64字符串
            header, data = image_data.split(',', 1)
            image_bytes = base64.b64decode(data)
        elif hasattr(image_data, 'read'):
            # 处理文件对象
            image_bytes = image_data.read()
        else:
            raise ValueError("不支持的图像数据格式")
            
        # 生成唯一文件名
        filename = f"{uuid.uuid4().hex}.{format}"
        folder_key = f"{folder_type.upper()}_FOLDER"
        if folder_key not in app.config:
            raise ValueError(f"未找到配置项: {folder_key}")
            
        save_path = os.path.join(app.config[folder_key], filename)
        
        # 保存图片
        with open(save_path, 'wb') as f:
            f.write(image_bytes)
            
        return f"/{folder_type}/{filename}"
    except Exception as e:
        app.logger.error(f"处理图像失败: {str(e)}")
        raise